package com.example.li_han.servlet;

import com.example.li_han.pojo.News;
import com.example.li_han.service.NewsService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 编辑新闻Servlet
 */
@WebServlet(name = "EditNewsServlet", value = "/EditNewsServlet")
public class EditNewsServlet extends HttpServlet {

    private String message;
    private Gson gson = new Gson();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sbuffer = new StringBuilder();
        String s;

        // 按行读取请求体
        while((s = br.readLine()) != null) {
            sbuffer.append(s);
        }

        String requestBody = sbuffer.toString();
        System.out.println("收到编辑请求: " + requestBody);

        Map<String, Object> resultMap = new HashMap<>();

        // 检查请求体是否为空
        if (requestBody == null || requestBody.trim().isEmpty()) {
            resultMap.put("code", 500);
            resultMap.put("msg", "请求体为空");
            sendJsonResponse(resp, resultMap);
            return;
        }

        try {
            // 使用Map先接收原始数据，便于调试和字段映射
            Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
            Map<String, Object> rawData = gson.fromJson(requestBody, mapType);

            // 检查解析结果是否为null
            if (rawData == null) {
                resultMap.put("code", 500);
                resultMap.put("msg", "JSON解析失败");
                sendJsonResponse(resp, resultMap);
                return;
            }

            System.out.println("解析后的原始数据: " + rawData);

            // 验证必要字段
            if (!rawData.containsKey("newsId") || rawData.get("newsId") == null) {
                resultMap.put("code", 500);
                resultMap.put("msg", "新闻ID不能为空");
                sendJsonResponse(resp, resultMap);
                return;
            }

            // 创建News对象并设置属性
            News news = new News();

            // 设置新闻ID
            Object newsIdObj = rawData.get("newsId");
            if (newsIdObj instanceof Double) {
                news.setNewsId(((Double) newsIdObj).intValue());
            } else if (newsIdObj instanceof Integer) {
                news.setNewsId((Integer) newsIdObj);
            } else {
                news.setNewsId(Integer.parseInt(newsIdObj.toString()));
            }

            // 设置typeId - 处理可能的类型转换
            if (rawData.containsKey("typeId") && rawData.get("typeId") != null) {
                Object typeIdObj = rawData.get("typeId");
                if (typeIdObj instanceof Double) {
                    news.setTypeId(((Double) typeIdObj).intValue());
                } else if (typeIdObj instanceof Integer) {
                    news.setTypeId((Integer) typeIdObj);
                } else {
                    news.setTypeId(Integer.parseInt(typeIdObj.toString()));
                }
            }

            // 设置其他字段
            if (rawData.containsKey("typeName") && rawData.get("typeName") != null) {
                news.setTypeName(rawData.get("typeName").toString());
            }

            if (rawData.containsKey("newsTitle") && rawData.get("newsTitle") != null) {
                news.setNewsTitle(rawData.get("newsTitle").toString());
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "新闻标题不能为空");
                sendJsonResponse(resp, resultMap);
                return;
            }

            if (rawData.containsKey("newsContent") && rawData.get("newsContent") != null) {
                news.setNewsContent(rawData.get("newsContent").toString());
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "新闻内容不能为空");
                sendJsonResponse(resp, resultMap);
                return;
            }

            if (rawData.containsKey("newsImage") && rawData.get("newsImage") != null) {
                news.setNewsImage(rawData.get("newsImage").toString());
            }

            // 设置布尔字段
            if (rawData.containsKey("isTop") && rawData.get("isTop") != null) {
                news.setTop(Boolean.parseBoolean(rawData.get("isTop").toString()));
            }

            if (rawData.containsKey("isShowHome") && rawData.get("isShowHome") != null) {
                news.setShowHome(Boolean.parseBoolean(rawData.get("isShowHome").toString()));
            }

            if (rawData.containsKey("isImageNews") && rawData.get("isImageNews") != null) {
                news.setImageNews(Boolean.parseBoolean(rawData.get("isImageNews").toString()));
            }

            // 设置viewCount
            if (rawData.containsKey("viewCount") && rawData.get("viewCount") != null) {
                Object viewCountObj = rawData.get("viewCount");
                if (viewCountObj instanceof Double) {
                    news.setViewCount(((Double) viewCountObj).intValue());
                } else if (viewCountObj instanceof Integer) {
                    news.setViewCount((Integer) viewCountObj);
                } else {
                    news.setViewCount(Integer.parseInt(viewCountObj.toString()));
                }
            }

            System.out.println("转换后的新闻对象: ID=" + news.getNewsId() + ", 标题=" + news.getNewsTitle());

            // 调用业务方法
            NewsService newsService = new NewsService();
            int flag = newsService.editNews(news);

            if(flag > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "编辑成功");
                resultMap.put("data", new HashMap<String, Object>() {{
                    put("newsId", news.getNewsId());
                    put("title", news.getNewsTitle());
                }});
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "编辑失败，可能是新闻不存在或其他原因");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器异常: " + e.getMessage());
        }

        sendJsonResponse(resp, resultMap);
    }

    // 发送JSON响应
    private void sendJsonResponse(HttpServletResponse resp, Map<String, Object> resultMap) throws IOException {
        String json = gson.toJson(resultMap);
        resp.getWriter().append(json);
    }
}